package com.zsk.tool.swing;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class BarCode extends JFrame {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private JPanel panel;

    private volatile int[] data = new int[30];

    boolean goRight = true;

    public void init() {
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        panel = new JPanel() {
            private static final long serialVersionUID = 1L;

            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                draw((Graphics2D)g);
            }
        };
        add(panel);
        setVisible(true);
        validate();

        new Thread() {
            @Override
            public void run() {
                while (true) {
                    Random random = new Random();
                    for (int i = 0; i < data.length; i++) {
                        data[i] = random.nextInt(5) + 1;
                    }
                    panel.repaint();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            };
        }.start();

    }

    private void draw(Graphics2D g) {

        g.setPaint(Color.BLACK);
        int x = 200;
        int y = 100;
        for (int i : data) {
            g.fillRect(x, y, i, 100);
            g.drawString(i + "", x - 2, y + 115);
            x += (i + 10);
        }

    }

    public static void main(String[] args) {
        new BarCode().init();
    }

}
